package com.des1gn;

import com.des1gn.mapper.AMapper;
import org.apache.ibatis.builder.xml.XMLConfigBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

/**
 * Hello world!
 *
 */
public class App {
    public static void main( String[] args ) throws IOException {
        Scanner scanner = new Scanner(System.in);
        //1\读取配置文件
        String resource = "mybatis-config.xml";
        String resourceMapper = "mybatis-config-mapper.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //2、初始化mybatis，创建SqlSessionFactory类实例
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        Configuration configuration = sqlSessionFactory.getConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        //3、创建Session实例
        SqlSession session = sqlSessionFactory.openSession();
        AMapper aMapper = session.getMapper(AMapper.class);
        System.out.println(aMapper.getName());

        while ((scanner.nextInt()==1)){
            //清除xml缓存
            sqlSessionFactory.getConfiguration().getMapperRegistry().clearCache();
            sqlSessionFactory.getConfiguration().clearMappedStatement();
            //重新加载xml
            InputStream inputStream2 = Resources.getResourceAsStream(resource);
            XMLConfigBuilder mapperBuilder = new XMLConfigBuilder(inputStream2, null, null);
            configuration = mapperBuilder.parseMapper();
            sqlSessionFactory.getConfiguration().setMapperRegistry(configuration.getMapperRegistry());
            sqlSessionFactory.getConfiguration().addMappedStatements(configuration.getMappedStatementNames(),configuration);
            sqlSessionFactory.getConfiguration().addLoadedResources(configuration.getLoadedResources());
            //3、创建Session实例
            session = sqlSessionFactory.openSession();
            AMapper aMapper1 = session.getMapper(AMapper.class);
            System.out.println(aMapper1.getName());
        }


    }
}
